import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTokenStore = defineStore(
  'token',
  () => {
    // Token 管理
    const token = ref<string>('')

    const setToken = (newToken: string) => {
      token.value = newToken
    }

    const removeToken = () => {
      token.value = ''
    }

    // 用户状态管理
    const isLoggedIn = ref(false)
    const userName = ref('')
    const unreadCount = ref(0)
    const id=ref(0)
    const selectedRole=ref(0)
    const login = (name: string, userId: number, newToken: string) => {
      isLoggedIn.value = true
      userName.value = name
      id.value=userId
      unreadCount.value = 5 // 模拟未读消息
      setToken(newToken)
      console.log('将id='+userId+"赋值给id"+id.value)
    }

    const logout = () => {
      isLoggedIn.value = false
      userName.value = ''
      unreadCount.value = 0
      removeToken()
    }

    return {
      // Token
      token,
      setToken,
      removeToken,
      // 用户信息
      isLoggedIn,
      userName,
      id,
      unreadCount,
      login,
      logout,
      selectedRole
    }
  },
  {
    persist: true // 会将所有 state 持久化
  }
)
